package com.xiaomage.view.draw10

import android.content.Context
import android.graphics.*
import android.view.View

/**
 * Created by Administrator on 2018/1/7.
 */
class MyView2(context: Context): View(context) {
    private val paint1=getPaint()
    private val paint2=getPaint()
    private val paint3=getPaint()
    private val paint4=getPaint()
    private val paint5=getPaint()
    private lateinit var bitmap: Bitmap
    private var bitmapHeight=0
    private lateinit var flowerBitmap: Bitmap
    init {
        bitmap= BitmapFactory.decodeResource(resources, R.drawable.dog)
        flowerBitmap= BitmapFactory.decodeResource(resources, R.drawable.flower)
        bitmapHeight=500*bitmap.height/bitmap.width
        //禁用硬件加速
        setLayerType(LAYER_TYPE_SOFTWARE,null)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        //新建图层
        val layerId=canvas.saveLayer(0f,0f,500f,bitmapHeight.toFloat(),
                paint1, Canvas.ALL_SAVE_FLAG)

        //核心代码
        canvas.drawBitmap(bitmap,null, Rect(0, 0, 500, bitmapHeight),paint1)
        paint1.xfermode= AvoidXfermode(Color.WHITE, 100, AvoidXfermode.Mode.TARGET)
        canvas.drawRect(0f,0f,500f,bitmapHeight.toFloat(),paint1)

        //还原图层
        canvas.restoreToCount(layerId)

    }
    private fun getPaint(): Paint {
        val paint= Paint()
        paint.isAntiAlias=true
        paint.style= Paint.Style.STROKE
        paint.strokeWidth=5f
        paint.color= Color.RED
        return paint
    }
}